<script setup lang="ts">
import type { patientConsultOrderDetailApi } from '@/types/room'
import { OrderType } from '@/enums'
import { ref } from 'vue'
import type { UploaderAfterRead } from 'vant/lib/uploader/types'
import { uploadImg } from '@/api/consult'
import { showLoadingToast } from 'vant'
defineProps<{
  orderInfo: patientConsultOrderDetailApi
}>()
const emits = defineEmits<{
  (e: 'sendMsg', txt: string): void
  (e: 'sendImage', img: { id: string; url: string }): void
}>()
const txt = ref('')
const keyupEvent = () => {
  if (txt.value === '') {
    return
  }
  // 将消息传递给父组件进行发送
  emits('sendMsg', txt.value)
  txt.value = ''
}

// 文件上传
const afterRead: UploaderAfterRead = async res => {
  // 类型守卫：缩小类型范围处理
  // 上传文件
  if (Array.isArray(res)) {
    return
  }
  if (!res.file) {
    return
  }
  // 上传中的loading
  const t = showLoadingToast({
    duration: 0,
    message: '加载中....'
  })
  try {
    const res2 = await uploadImg(res.file)
    emits('sendImage', res2.data)
  } finally {
    t.close()
  }
}
</script>

<template>
  <div class="room-action">
    <van-field
      :disabled="orderInfo.status !== OrderType.ConsultChat"
      type="text"
      class="input"
      :border="false"
      placeholder="问医生"
      autocomplete="off"
      v-model.trim="txt"
      @keyup.enter="keyupEvent"
    ></van-field>
    <van-uploader
      :disabled="orderInfo.status !== OrderType.ConsultChat"
      :preview-image="false"
      :after-read="afterRead"
    >
      <cp-icon name="consult-img" />
    </van-uploader>
  </div>
</template>

<style lang="scss" scoped>
.room-action {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 60px;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 1;
  box-sizing: border-box;
  .input {
    background-color: var(--cp-bg);
    border: none;
    border-radius: 25px;
    margin-right: 10px;
    padding: 8px 15px;
  }
  .cp-icon {
    width: 24px;
    height: 24px;
  }
}
</style>
